!function ($) {
    var DataRangeSlider = function (element, options) {
        this.target_el = "#" + element.id;
        this.storageId = element.id;
        if (options) _.extend(this, options);
    };

    DataRangeSlider.prototype = {
        constructor:DataRangeSlider,
        initialStep:600,
        min:0,
        max:100,

        init:function () {
            var foundStart = localStorage.getItem(this.storageId);
            this.rawValue = (foundStart) ? parseInt(foundStart) : this.initialStep;

            var me = this;
            $(this.target_el).slider({
                value:this.rawValue,
                min:100,
                max:1100,
                slide: function(event, ui) {
                    me.rawValue = ui.value;
                    localStorage.setItem(me.storageId, me.rawValue);
                    me._publishValues();
                }
            });

            this._publishValues();
        },

        _calculateSliderValue:function (rawValue) {
            if (rawValue === undefined) rawValue = this.rawValue;
            if (rawValue === undefined) return 0;

            var positionAsPercentage = ((rawValue - 100) / 10) / 100;
            return (Math.abs(this.max - this.min) * positionAsPercentage) + this.min;
        },

        _getDisplayValue:function (value) {
            var cutoff = (value > 0) ? 5 : 6;
            var strvalue = "" + value;
            if (strvalue.length > cutoff) return strvalue.substring(0, cutoff);
            return strvalue;
        },

        _resetSliderValue: function() {
            localStorage.removeItem(this.storageId);
            this.rawValue = this.initialStep;
            this._publishValues();
            $(this.target_el).slider("value", this.rawValue);
        },

        _publishValues: function() {
            if (this.slide) {
                var calcValue = this._calculateSliderValue(this.rawValue);
                var displayValue = this._getDisplayValue(calcValue);
                this.slide({ "raw":this.rawValue, "calculated":calcValue, "display":displayValue });
            }
        }
    };

    // jQuery Plugin
    $.fn.datarange = function (options) {
        return this.each(function () {
            var $this = $(this);
            var ft = $this.data("DataRangeSlider");
            if (!ft) $this.data("DataRangeSlider", (ft = new DataRangeSlider(this, options)));
            ft.init();
        });
    };

    $.fn.datarange_calculated = function () {
        var $this = $(this);
        var ft = $this.data("DataRangeSlider");
        if (ft) return ft._calculateSliderValue();
        return 0;
    };

    $.fn.datarange_reset = function() {
        var $this = $(this);
        var ft = $this.data("DataRangeSlider");
        if (ft) return ft._resetSliderValue();
    };

}(window.jQuery);
